﻿using StudentInfoSystem.Core.Models.Enums;
using StudentInfoSystem.Core.Utils;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Windows;

namespace StudentInfoSystem.Core.Models;


/// <summary>
///  【注意】 TitleBar是直接持有该实例，SettingView是通过构造函数在MainWindowViewModel传入改实例，然后把实例丢给SettingViewModel
/// </summary>
public class AppSettings : INotifyPropertyChanged
{
    private static AppSettings? _instance;
    public static AppSettings Instance
    {
        get
        {
            if (_instance == null)
            {
                try
                {
                    _instance = JsonData.Load<AppSettings>();
                    _instance.ValidateEncryption(); // 验证加密数据
                }
                catch
                {
                    _instance = new AppSettings(); // 降级处理
                }

            }
            return _instance;
        }
    }

    // 所有属性都需要实现属性变更通知

    public event PropertyChangedEventHandler? PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        AutoSave();
    }

    protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
    {
        if (EqualityComparer<T>.Default.Equals(field, value)) return false;
        field = value;
        OnPropertyChanged(propertyName);
        return true;
    }

    // 自动保存方法
    private CancellationTokenSource? _saveToken;
    private async void AutoSave()
    {
        _saveToken?.Cancel();
        _saveToken = new CancellationTokenSource();

        try
        {
            await Task.Delay(500, _saveToken.Token);
            await JsonData.SaveAsync(this);
        }
        catch (TaskCanceledException) { /* 正常取消 */ }
    }

    private Dictionary<string, bool> _featureToggles = [];
    [JsonIgnore]
    public Dictionary<string, bool> FeatureToggles
    {
        get => _featureToggles;
        set => SetField(ref _featureToggles, value);
    }


    // 支持任意类型的数据存储
    [JsonExtensionData]
    public Dictionary<string, JsonElement>? ExtensionData { get; set; }


    // ===================================== 设置 ======================================

    private bool _isDarkTheme = true;
    public bool IsDarkTheme
    {
        get => _isDarkTheme;
        set => SetField(ref _isDarkTheme, value);
    }

    // 背景图片按钮是否启用
    private bool _isBackgroundImageEnabled = true;
    public bool IsBackgroundImageEnabled
    {
        get => _isBackgroundImageEnabled;
        set => SetField(ref _isBackgroundImageEnabled, value);
    }

    // 侧边栏菜单按钮光效是否启用
    private Visibility _buttonEffectVisibility = Visibility.Visible;
    public Visibility ButtonEffectVisibility
    {
        get => _buttonEffectVisibility;
        set => SetField(ref _buttonEffectVisibility, value);
    }

    private bool _autoSaveEnabled = true;
    public bool AutoSaveEnabled
    {
        get => _autoSaveEnabled;
        set => SetField(ref _autoSaveEnabled, value);
    }

    private int _saveInterval = 15; // 默认15分钟
    public int SaveInterval
    {
        get => _saveInterval;
        set => SetField(ref _saveInterval, value);
    }

    private string _backgroundImagePath = "";
    public string BackgroundImagePath
    {
        get => _backgroundImagePath;
        set => SetField(ref _backgroundImagePath, value);
    }
    // ===================================== 公开方法 ======================================
    public void RefreshAllProperties()
    {
        // 手动触发所有属性的 PropertyChanged 事件
        var properties = this.GetType().GetProperties();
        foreach (var property in properties)
        {
            OnPropertyChanged(property.Name);
        }
    }
    public void ValidateEncryption()
    {
        try
        {
            // 测试加密解密是否正常工作
            var testText = "test";
            var encrypted = SecurityHelper.SimpleEncrypt(testText);
            var decrypted = SecurityHelper.SimpleDecrypt(encrypted);

            if (testText != decrypted)
            {
                // 加密解密不匹配，重置所有加密数据
                _lastUsername = "";
                _lastPassword = "";
                _currentUser = null;

                // 重新加密所有用户账户
                foreach (var account in UserAccounts)
                {
                    var tempPassword = SecurityHelper.SimpleDecrypt(account.PasswordHash);
                    account.PasswordHash = SecurityHelper.SimpleEncrypt(tempPassword);
                }
            }
        }
        catch
        {
            // 加密系统有问题，重置所有加密数据
            _lastUsername = "";
            _lastPassword = "";
            _currentUser = null;
        }
    }
    // ===================================== 配置信息 ======================================
    private int _savedPageSize = 10;
    public int SavedPageSize
    {
        get => _savedPageSize;
        set => SetField(ref _savedPageSize, value);
    }

    private bool _savedIsSortOptionAscending = true;
    public bool SavedIsSortOptionAscending
    {
        get => _savedIsSortOptionAscending;
        set => SetField(ref _savedIsSortOptionAscending, value);
    }

    private SearchField? _savedSearchField;
    public SearchField? SavedSearchField
    {
        get => _savedSearchField;
        set => SetField(ref _savedSearchField, value);
    }

    private SortOption _savedSortOption;
    public SortOption SavedSortOption
    {
        get => _savedSortOption;
        set => SetField(ref _savedSortOption, value);
    }

    // 数据库文件路径
    private string? _savedDataBasePath;
    public string? SavedDataBasePath {
        get => _savedDataBasePath;
        set => SetField(ref _savedDataBasePath, value);
    }

    // 在AppSettings类中添加以下字段和属性
    private ObservableCollection<UserAccount> _userAccounts = new ObservableCollection<UserAccount>();
    public ObservableCollection<UserAccount> UserAccounts
    {
        get => _userAccounts;
        set => SetField(ref _userAccounts, value);
    }

    private bool _isFirstRun = true;
    public bool IsFirstRun
    {
        get => _isFirstRun;
        set => SetField(ref _isFirstRun, value);
    }

    private string _lastUsername = "";
    public string LastUsername
    {
        get => SecurityHelper.SimpleDecrypt(_lastUsername);
        set => SetField(ref _lastUsername, SecurityHelper.SimpleEncrypt(value));
    }

    private string _lastPassword = "";
    public string LastPassword
    {
        get => SecurityHelper.SimpleDecrypt(_lastPassword);
        set => SetField(ref _lastPassword, SecurityHelper.SimpleEncrypt(value));
    }
    private bool _isRememberPassword = false;
    public bool IsRememberPassword
    {
        get => _isRememberPassword;
        set => SetField(ref _isRememberPassword, value);
    }

    // 在 AppSettings 类中添加以下属性
    private List<UserAccount> _initialAdminAccounts = new(){
        new UserAccount
        {
            Username = "admin",
            Email = "admin@school.com",
            PasswordHash = SecurityHelper.SimpleEncrypt("admin123"),
            IsAdmin = true
        },
        new UserAccount
        {
            Username = "supervisor",
            Email = "supervisor@school.com",
            PasswordHash = SecurityHelper.SimpleEncrypt("supervisor123"),
            IsAdmin = true
        }
    };

    [JsonIgnore]
    public List<UserAccount> InitialAdminAccounts => _initialAdminAccounts;

    // 在 AppSettings 类中添加以下属性
    private UserAccount? _currentUser;

    public UserAccount? CurrentUser
    {
        get
        {
            if (_currentUser == null) return null;

            // 返回解密后的用户信息
            return new UserAccount
            {
                Username = SecurityHelper.SimpleDecrypt(_currentUser.Username),
                Email = SecurityHelper.SimpleDecrypt(_currentUser.Email),
                PasswordHash = _currentUser.PasswordHash, // 密码哈希已经是加密的
                RememberMe = _currentUser.RememberMe,
                IsAdmin = _currentUser.IsAdmin
            };
        }
        set
        {
            if (value == null)
            {
                SetField(ref _currentUser, null);
                return;
            }

            // 加密存储用户信息
            var encryptedAccount = new UserAccount
            {
                Username = SecurityHelper.SimpleEncrypt(value.Username),
                Email = SecurityHelper.SimpleEncrypt(value.Email),
                PasswordHash = value.PasswordHash, // 密码哈希已经是加密的
                RememberMe = value.RememberMe,
                IsAdmin = value.IsAdmin
            };

            SetField(ref _currentUser, encryptedAccount);
        }
    }

    private bool _isAutoLogin = false;
    public bool IsAutoLogin
    {
        get => _isAutoLogin;
        set => SetField(ref _isAutoLogin, value);
    }

}